package global

import (
	"fmt"
	"github.com/spf13/viper"
	"path"
)

type AppEnv string

const (
	AppEnvDev   AppEnv = "dev"
	AppEnvTest  AppEnv = "test"
	AppEnvProd  AppEnv = "prod"
	AppEnvLocal AppEnv = "local"
)

func (a AppEnv) String() string {
	return string(a)
}

var AppEnvConfig AppEnv

func getEnvInfo(env string) AppEnv {
	viper.AutomaticEnv()
	envStr := viper.GetString(env)
	fmt.Println("Load env_str :", envStr)
	envArr := []AppEnv{AppEnvDev, AppEnvTest, AppEnvProd, AppEnvLocal}
	for _, e := range envArr {
		if envStr == e.String() {
			return e
		}
	}
	return AppEnvLocal
}

func InitViperConfig(workDir string, config interface{}) {
	AppEnvConfig = getEnvInfo("APP_ENV")
	fmt.Println("Load config path:", workDir)
	var configFileName string
	switch AppEnvConfig {
	case AppEnvProd:
		{
			// 生产环境
			configFileName = path.Join(workDir, "application.prod.yml")
			fmt.Println("now env is product")
		}
	case AppEnvTest:
		{
			// 测试环境
			configFileName = path.Join(workDir, "application.test.yml")
			fmt.Println("now env is test")
		}
	case AppEnvDev:
		{
			// 开发环境
			configFileName = path.Join(workDir, "application.dev.yml")
			fmt.Println("now env is dev")
		}
	default:
		{
			// 本地开发环境
			// 这里要改为./ 不然本地起不来
			configFileName = path.Join("./", "application.dev.yml")
			fmt.Println("now local env is developer")
		}

	}
	fmt.Println("Config filename:", configFileName)
	v := viper.New()
	//文件的路径如何设置
	v.SetConfigFile(configFileName)
	if err := v.ReadInConfig(); err != nil {
		panic(err)
	}
	if err := v.Unmarshal(config); err != nil {
		panic(err)
	}
	if _, err := fmt.Printf("Load config content : %v", config); err != nil {
		panic(err)
	}
}
